package com.itbupt.eat.controller;

import com.itbupt.eat.common.R;
import com.itbupt.eat.entity.AddressBook;
import com.itbupt.eat.service.impl.AddressBookServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author BUPT-Dingchang
 * @Create 2024/5/2 2:03
 * ClassName: AddressBookController
 * Description:
 */

@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookServiceImpl addressBookService;


    /**
     * 新增地址
     * @param addressBook   地址信息
     * @return  地址信息
     */
    @PostMapping
    public R<AddressBook> save(@RequestBody AddressBook addressBook) {
        return R.success(addressBookService.saveAdd(addressBook));
    }

    /**
     * 地址展示
     * @return  地址列表
     */
    @GetMapping("/list")
    public R<List<AddressBook>> getList() {
        return R.success(addressBookService.getList());
    }

    /**
     * 设置默认地址
     * @param addressBook   地址信息
     * @return  地址信息
     */
    @PutMapping("/default")
    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook) {
        return R.success(addressBookService.setDefault(addressBook));
    }


    /**
     * 查询单个地址的信息，用于编辑回显
     * @param id    地址id
     * @return  地址信息
     */
    @GetMapping("/{id}")
    public R<AddressBook> getAdd(@PathVariable Long id) {
        AddressBook addressBook = addressBookService.getById(id);
        if (addressBook != null) {
            return R.success(addressBook);
        }
        return R.error("没有找到该对象");
    }


    /**
     * 更新地址
     * @param addressBook   地址信息
     * @return  新的地址信息
     */
    @PutMapping
    public R<String> updateAdd(@RequestBody AddressBook addressBook) {
        if (addressBookService.updateById(addressBook)) {
            return R.success("保存成功");
        }
        return R.success("保存失败");
    }


    /**
     * 删除地址
     * @param ids   地址id
     * @return  删除结果
     */
    @DeleteMapping
    public R<String> remove(@RequestParam Long ids) {
        if (addressBookService.removeById(ids)) {
            return R.success("删除成功");
        }
        return R.error("删除失败");
    }


    /**
     * 获取当前用户的默认地址
     * @return  地址信息
     */
    @GetMapping("/default")
    public R<AddressBook> getDefault() {
        return R.success(addressBookService.getDefault());
    }


}
